package com.fyales.android.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
import static android.net.ConnectivityManager.TYPE_DUMMY;
import static android.net.ConnectivityManager.TYPE_ETHERNET;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.ConnectivityManager.TYPE_WIMAX;

public class NetWorkUtil {
    public static boolean isNetWorkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        return info != null && info.isAvailable();
    }

    public static String getNetworkTypeName(Context context) {
        int type = -1;
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null)
            type = info.getType();
        switch (type) {
        case TYPE_MOBILE:
            return "MOBILE";
        case TYPE_WIFI:
            return "WIFI";
        case TYPE_MOBILE_DUN:
            return "MOBILE_DUN";
        case TYPE_WIMAX:
            return "WIMAX";
        case TYPE_BLUETOOTH:
            return "BLUETOOTH";
        case TYPE_DUMMY:
            return "DUMMY";
        case TYPE_ETHERNET:
            return "ETHERNET";
        default:
            return Integer.toString(type);
        }
    }

    public static List<String> getLocalDns() {
        List<String> servers = new ArrayList<String>();
        try {
            Class<?> SystemProperties = Class
                    .forName("android.os.SystemProperties");
            Method method = SystemProperties.getMethod("get",
                    new Class[] { String.class });
            for (String name : new String[] { "net.dns1", "net.dns2",
                    "net.dns3", "net.dns4", }) {
                String value = (String) method.invoke(null, name);
                if (value != null && !"".equals(value)
                        && !servers.contains(value)) {
                    servers.add(value);
                }
            }
        } catch (Exception e) {
        }
        return servers;
    }
}
